package com.scut.statistics_website.service;

import com.scut.statistics_website.config.GlobalVariables;
import com.scut.statistics_website.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class StatisticsService {
    @Autowired
    private RedisUtil redisUtil;

    public ArrayList<Float> getSuccessRates(){
        int listSize = (int)redisUtil.lGetListSize(GlobalVariables.SUCCESS_RATE_LIST);
        List<Object> rawSuccessRates = null;
        if (listSize >= GlobalVariables.REAL_TIME_LENGTH) {
            rawSuccessRates = redisUtil.lGet(GlobalVariables.SUCCESS_RATE_LIST, listSize - GlobalVariables.REAL_TIME_LENGTH, listSize);
        }
        else {
            rawSuccessRates = redisUtil.lGet(GlobalVariables.SUCCESS_RATE_LIST, 0, listSize);
        }
        ArrayList<Float> successRates = new ArrayList<>(listSize);
        for (Object rawSuccessRate : rawSuccessRates) {
            successRates.add(Float.parseFloat(rawSuccessRate.toString()) * 100);
        }
        return successRates;
    }

    public ArrayList<Float> getAvgAnswerTimes(){
        int listSize = (int)redisUtil.lGetListSize(GlobalVariables.AVG_ANSWER_TIME_LIST);
        List<Object> rawAvgAnswerTimes = null;
        if (listSize >= GlobalVariables.REAL_TIME_LENGTH) {
            rawAvgAnswerTimes = redisUtil.lGet(GlobalVariables.AVG_ANSWER_TIME_LIST, listSize - GlobalVariables.REAL_TIME_LENGTH, listSize);
        }
        else {
            rawAvgAnswerTimes = redisUtil.lGet(GlobalVariables.AVG_ANSWER_TIME_LIST, 0, listSize);
        }
        ArrayList<Float> avgAnswerTimes = new ArrayList<>(listSize);
        for (Object rawAvgAnswerTime : rawAvgAnswerTimes) {
            avgAnswerTimes.add(Float.parseFloat(rawAvgAnswerTime.toString()));
        }
        return avgAnswerTimes;
    }

    public float getAvgAnswerTime(){
        return Float.parseFloat(redisUtil.get(GlobalVariables.AVG_ANSWER_TIME).toString());
    }

    public float getSuccessRate() {
        int successDemandsCount = (int)redisUtil.get(GlobalVariables.SUCCESS_DEMAND_COUNT);
        int demandCount = (int)redisUtil.get(GlobalVariables.DEMAND_COUNT);
        return (float)successDemandsCount / demandCount;
    }

    public float getExpiredRate() {
        int expiredDemandCount = (int)redisUtil.get(GlobalVariables.EXPIRED_DEMAND_COUNT);
        int demandCount = (int)redisUtil.get(GlobalVariables.DEMAND_COUNT);
        return (float)expiredDemandCount / demandCount;
    }
}
